package com.xk._02算法篇._01sort.sort;

import com.xk.tools.Integers;

/**
 * @description: 基数排序
 * @author: xu
 * @date: 2022/10/2 10:43
 */
public class RadixSort extends Sort<Integer> {
    /**
     * 基数排序
     */
    private void radixSort(){
        // 找出最大值
        int max = array[0];
        for (int i = 1; i < array.length; i++) {
            if (array[i] > max) max = array[i];
        }
        for (int divider = 1; divider <= max; divider *= 10){
            countingSort(divider);
        }
    }

    /**
     * 计数排序
     */
    private void countingSort(int divider){
        //开辟内存空间，存储次数
        int[] counts = new int[10];
        // 统计每个位数出现的次数
        for (int i = 0; i < array.length; i++) {
            counts[array[i] / divider % 10]++;
        }
        // 累加次数
        for (int i = 1; i < counts.length; i++) {
            counts[i] += counts[i - 1];
        }
        // 从后往前遍历元素，将它放到有序数组中的合适位置
        Integer[] newArray = new Integer[array.length];
        for (int i = array.length - 1; i >= 0; i--) {
            int index = --counts[array[i] / divider % 10];
            newArray[index] = array[i];
        }
        // 将有序数组赋值到array
        for (int i = 0; i < newArray.length; i++) {
            array[i] = newArray[i];
        }
    }

    @Override
    protected void sort() {
        radixSort();
    }

    public static void main(String[] args) {
        Integer[] array = Integers.random(32, 1, 100);
        Integers.println(array);

        Sort<Integer> mergeSort = new RadixSort();
        mergeSort.sort(array);
        Integers.println(array);
        System.out.println(mergeSort);
    }
}
